<template>

  <div class="app-container">
    <el-breadcrumb separator="/" style="padding: 20px;background-color: #f9f9f9">
      <el-breadcrumb-item>{{charge.name}}</el-breadcrumb-item>
      <el-breadcrumb-item>{{charge.subTitle}}</el-breadcrumb-item>

    </el-breadcrumb>

    <div class="content-container">


      <div class="left_content" v-if="!charge.isSingle">
        <div class="top_row_bar">
          <el-link icon="el-icon-edit" @click="addFun();">新增</el-link>
          <el-link icon="el-icon-share" @click="addChildFun();">下级</el-link>
          <el-link icon="el-icon-edit" @click="edit();">修改</el-link>
          <el-link icon="el-icon-delete" @click="reloadTree();">删除</el-link>
        </div>
        <el-tree
          ref="treeCategory"
          :props="props"
          :load="loadNode"
          lazy
          node-key="id"
          :check-on-click-node="true"
          @node-click="treeSelect"
          class="left_tree"
        >
        </el-tree>
      </div>

      <div class="right_content" v-if="charge.isSingle || (selectTreeNodeData && selectTreeNodeData.isLeaf) ">

        <div style="width: 1000px">
          <el-form
            ref="calculateDataForm"
            :rules="calculateRules"
            :model="calculateForm"
            status-icon
            label-position="left"
            label-width="100px"
            style="width: 100%; "
          >
            <!--
            <el-form-item label="id" prop="id">
              <el-input v-model="calculateForm.id"/>
            </el-form-item>

            <el-form-item label="cateId" prop="cateId">
              <el-input v-model="calculateForm.cateId"/>
            </el-form-item>

            <el-form-item label="chargeId" prop="chargeId">
              <el-input v-model="calculateForm.chargeId"/>
            </el-form-item>-->

            <el-form-item label="计费名称" prop="labelName">
              <el-input v-model="calculateForm.labelName"/>
            </el-form-item>

            <el-form-item label="下限（不足）" prop="lowerLimit">
              <el-input-number v-model="calculateForm.lowerLimit" :precision="4" :step="10" style="width: 300px;">
              </el-input-number>
            </el-form-item>

            <el-form-item label="上限（超出）" prop="upperLimit">
              <el-input-number v-model="calculateForm.upperLimit" :precision="4" :step="10" style="width: 300px;">
              </el-input-number>
            </el-form-item>

            <div v-if="calculateForm.id">
              <div class="filter-container">
                <el-button
                  class="filter-item"
                  type="success"
                  size="small"
                  icon="el-icon-edit"
                  @click="handleItemAdd"
                >添加
                </el-button>
              </div>
              <el-table :header-cell-style="{background:'#f5f5f5',color:'#333333',height:'50px'}"
                        :data="calculateForm.items"
                        element-loading-text="正在查询中..." border fit highlight-current-row>

                <el-table-column align="center" label="排序" width="100" prop="sortIndex"/>

                <el-table-column align="center" label="计算率方式" prop="type">
                  <template slot-scope="scope">
                    <div>
                      {{ scope.row.type
                      |calculateTypeFormat}}
                    </div>
                  </template>
                </el-table-column>

                <el-table-column align="center" label="下限" prop="lowerLimit">
                  <template slot-scope="scope">
                      <div>{{scope.row.lowerLimit}} ({{scope.row.lowerLimit |numberToChinese}})</div>
                  </template>

                </el-table-column>

                <el-table-column align="center" label="上限" prop="upperLimit">

                  <template slot-scope="scope">
                    <div>{{scope.row.upperLimit}} ({{scope.row.upperLimit |numberToChinese}})</div>
                  </template>
                </el-table-column>

                <el-table-column align="center" label="准率" prop="fixNum"/>


                <el-table-column align="center" label="操作" width="200" class-name="small-padding fixed-width">
                  <template slot-scope="scope">
                    <el-button
                      type="primary"
                      size="mini"
                      @click="handleUpdateItems(scope.row)"
                    >修改
                    </el-button>

                    <el-button
                      type="danger"
                      size="mini"
                      @click="handleDeleteItems(scope.row)"
                    >删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>


          </el-form>
          <div slot="footer" class="dialog-footer calculate-footer">
            <el-button type="primary" @click="saveCalculate" :loading="saveCalculateLoading">确定保存</el-button>
          </div>
        </div>

        <!-- 明细计费对话框 -->
        <el-dialog title="明细计算编辑" :visible.sync="dialogItemsFormVisible">
          <el-form
            ref="itemsForm"
            :rules="rulesItems"
            :model="itemsForm"
            status-icon
            label-position="left"
            label-width="100px"
            style="width: 600px; margin-left:50px;"
          >
            <!--
            <el-form-item label="id" prop="id">
              <el-input v-model="itemsForm.id"/>
            </el-form-item>

            <el-form-item label="cuId" prop="cuId">
              <el-input v-model="itemsForm.cuId"/>
            </el-form-item>-->


            <el-form-item label="排序" prop="sortOrder">
              <el-input-number v-model="itemsForm.sortIndex" :step="10" style="width: 300px;">
              </el-input-number>
            </el-form-item>

            <el-form-item label="下限" prop="lowerLimit">
              <el-input-number v-model="itemsForm.lowerLimit"  :precision="4" :step="10" style="width: 300px;">
              </el-input-number>
              <span>{{itemsForm.lowerLimit|numberToChinese}}</span>
            </el-form-item>

            <el-form-item label="上限" prop="upperLimit">
              <el-input-number v-model="itemsForm.upperLimit" placeholder="-1无上限" :precision="4" :step="10"
                               style="width: 300px;">
              </el-input-number>
              <span>{{itemsForm.upperLimit |numberToChinese}}</span>
            </el-form-item>

            <el-form-item label="计算率方式" prop="type">

              <el-radio-group v-model="itemsForm.type">
                <el-radio-button :label="0">%（百分比）</el-radio-button>
                <el-radio-button :label="1">‰（千分比）</el-radio-button>
                <el-radio-button :label="2">固定值</el-radio-button>
                <el-radio-button :label="3">区间</el-radio-button>
              </el-radio-group>

            </el-form-item>

            <el-form-item label="值" prop="fixNum" v-if="itemsForm.type != 3 ">
              <el-input-number v-model="itemsForm.fixNum" :precision="4" :step="10" style="width: 300px;">
              </el-input-number>
            </el-form-item>

            <el-form-item label="下限区间值" prop="lowerArea" v-if="itemsForm.type == 3">
              <el-input-number v-model="itemsForm.lowerArea" :precision="4" :step="10" style="width: 300px;">
              </el-input-number>
            </el-form-item>

            <el-form-item label="上限区间值" prop="upperArea" v-if="itemsForm.type == 3">
              <el-input-number v-model="itemsForm.upperArea" :precision="4" :step="10" style="width: 300px;">
              </el-input-number>
            </el-form-item>


          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogItemsFormVisible = false">取消</el-button>
            <el-button type="primary" :loading="saveItemsLoading" @click="saveItemFun">确定</el-button>
          </div>
        </el-dialog>

      </div>


      <!-- 添加或修改对话框 -->
      <el-dialog title="分类编辑" :visible.sync="dialogFormVisible">
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="dataForm"
          status-icon
          label-position="left"
          label-width="100px"
          style="width: 400px; margin-left:50px;"
        >
          <el-form-item label="id" prop="id">
            <el-input v-model="dataForm.id"/>
          </el-form-item>

          <el-form-item label="pid" prop="pid">
            <el-input v-model="dataForm.pid"/>
          </el-form-item>

          <el-form-item label="chargeId" prop="chargeId">
            <el-input v-model="dataForm.chargeId"/>
          </el-form-item>

          <el-form-item label="分类名称" prop="name">
            <el-input v-model="dataForm.name"/>
          </el-form-item>


          <el-form-item label="排序" prop="sortOrder">
            <el-input-number v-model="dataForm.sortIndex" :step="10" style="width: 300px;">
            </el-input-number>
          </el-form-item>


          <el-form-item label="分类/叶子" prop="isLeaf">
            <el-switch v-model="dataForm.isLeaf" :active-value="true"
                       :inactive-value="false"
                       active-text="叶子"
                       inactive-text="分类"/>
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="createData">确定</el-button>
        </div>
      </el-dialog>


    </div>
  </div>


</template>

<style>


  .content-container {
    display: flex;
    min-height: calc(100vh - 100px);
  }

  .calculate-footer {
    text-align: right;
    width: 100%;
    margin-top: 30px;
  }

  .left_content {
    padding: 20px;
    width: 500px;
    background-color: #f9f9f9;

  }


  .left_tree {
    background-color: #f9f9f9;
  }

  .left_tree .el-tree-node.is-current > .el-tree-node__content {
    background-color: rgb(64, 158, 255) !important;
    color: #fff;
  }

  .top_row_bar {
    display: flex;
    align-items: flex-end;
    justify-content: right;
    padding-right: 20px;
    margin-bottom: 20px;
  }

  .top_row_bar .el-link {
    margin-left: 10px;
  }

  .right_content {
    flex: 1;
    padding-top: 20px;
    padding-left: 40px;
  }
</style>

<script>
  import { categoryList, categoryDelete, categoryCreate } from '../../api/standardCategory'
  import { chargeDetail } from '../../api/standardCharges'
  import { calculateDetail, calculateSave } from '../../api/standardCalculate'
  import { calculateItemSave, calculateItemDel } from '../../api/standardCalculateItem'

  export default {
    name: 'Calculate',
    components: {},
    data() {
      return {
        chargeId: undefined,
        charge: {
          isSingle: true
        },

        dialogFormVisible: false,
        props: {
          id: 'id',
          label: 'name',
          isLeaf: 'isLeaf'

        },
        resolveFunc: null,
        selectTreeNodeData: undefined,
        dataForm: {
          id: undefined,
          name: undefined,
          pid: 0,
          chargeId: undefined,
          sortIndex: 100,
          isLeaf: false
        },
        //计算公式
        calculateForm: {
          id: undefined,
          chargeId: undefined,
          cateId: undefined,
          labelName: '',
          lowerLimit: undefined,
          upperLimit: undefined,
          items: []
        },
        //明细
        itemsForm: {
          id: undefined,
          cuId: undefined,
          lowerLimit: undefined,
          upperLimit: undefined,
          sortIndex: 100,
          type: 0,
          fixNum: undefined,
          fixNumUpper: undefined
        },

        dialogItemsFormVisible: false,

        saveCalculateLoading: false,

        saveItemsLoading: false,
        rules: {
          sortIndex: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
          name: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ],
          pid: [
            { required: true, message: 'pId不能为空', trigger: 'blur' }
          ]

        },
        calculateRules: {
          labelName: [
            { required: true, message: '名称不能为空', trigger: 'blur' }
          ]

        },
        rulesItems: {
          lowerLimit: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ],
          upperLimit: [
            { required: true, message: '不能为空', trigger: 'blur' }
          ]

        }
      }
    },
    computed: {},
    created() {
      this.chargeId = this.$route.query.chargeId
      this.chargeDetail()
    },
    methods: {
      //计费标准详情
      chargeDetail() {
        let that = this
        chargeDetail(this.chargeId).then(res => {
          that.charge = res.data.data
          console.log(that.charge)
          if (this.charge.isSingle) {
            this.resetCalculateForm(null)
            this.calculateDetailFun(this.charge.id, null)
          }

        }).catch(err => {
          console.log(err)
        })
      },
      treeSelect(data, node) {
        this.selectTreeNodeData = data
        console.log(data)
        console.log(node)
        if (this.selectTreeNodeData.isLeaf) {
          this.resetCalculateForm(this.selectTreeNodeData.id)
          this.calculateDetailFun(this.chargeId, this.selectTreeNodeData.id)
        }
      },
      loadNode(node, resolve) {
        let that = this
        let pid = ''
        if (node) {
          let nodeData = node.data

          if (nodeData) {
            pid = nodeData.id
          }
        }

        categoryList({
          chargeId: that.chargeId,
          pid: pid
        }).then(res => {
          //console.log(res.data)
          if (res.data.errno == 0) {
            console.log(res.data.data)
            return resolve(res.data.data)
          }
        })
        //return resolve([{ name: 'region' }])

      },
      resetForm() {
        this.dataForm = {
          id: undefined,
          name: undefined,
          pid: 0,
          chargeId: this.chargeId,
          sortIndex: 100,
          isLeaf: false
        }
      },
      addFun() {
        this.resetForm()
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      addChildFun() {
        if (this.selectTreeNodeData) {
          this.resetForm()
          this.dataForm.pid = this.selectTreeNodeData.id
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          this.$notify.error({
            title: '失败',
            message: '请选择'
          })
        }
      },

      reloadTree() {
        try {
          let that = this
          categoryList({
            chargeId: that.chargeId,
            pid: 0
          }).then(res => {
            //console.log(res.data)
            if (res.data.errno == 0) {
              console.log(res.data.data)
              that.$refs.treeCategory.root.setData(res.data.data)
              //return resolve(res.data.data)
            }
          })

        } catch (e) {
          console.error(e)
        }

      },
      edit() {
        if (this.selectTreeNodeData) {
          this.resetForm()
          this.dataForm = Object.assign(this.dataForm, this.selectTreeNodeData)
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          this.$notify.error({
            title: '失败',
            message: '请选择'
          })
        }

      },

      createData() {
        let that = this
        this.$refs['dataForm'].validate(valid => {
          if (valid) {
            console.log(this.dataForm)
            categoryCreate(this.dataForm)
              .then(response => {

                this.dialogFormVisible = false
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
                that.reloadTree()
              })
              .catch(err => {
                console.log(err)
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      //
      resetCalculateForm(cateId) {
        this.calculateForm = {
          id: undefined,
          chargeId: this.chargeId,
          cateId: cateId,
          labelName: '',
          lowerLimit: undefined,
          upperLimit: undefined,
          items: []
        }
      },
      //计算公式
      calculateDetailFun(chargeId, cateId) {
        let that = this
        calculateDetail({
          chargeId,
          cateId
        }).then(res => {
          if (res.data.data) {
            that.calculateForm = Object.assign(that.calculateForm, res.data.data)
            console.log(that.calculateForm)
          }

        }).catch(err => {
          console.log(err)
        })
      },
      //保存计算公式
      saveCalculate() {
        let that = this
        this.$refs['calculateDataForm'].validate(valid => {
          if (valid) {
            that.saveCalculateLoading = true
            console.log(this.calculateForm)
            calculateSave(this.calculateForm)
              .then(response => {
                that.saveCalculateLoading = false
                that.calculateDetailFun(that.chargeId, that.calculateForm.cateId)
                this.$notify.success({
                  title: '成功',
                  message: '创建成功'
                })
              })
              .catch(err => {
                that.saveCalculateLoading = false
                console.log(err)
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      },
      //明细
      resetItemsForm() {
        this.itemsForm = {
          id: undefined,
          cuId: this.calculateForm.id,
          lowerLimit: undefined,
          upperLimit: undefined,
          sortIndex: 100,
          type: 0,
          fixNum: undefined,
          fixNumUpper: undefined
        }
      },
      handleItemAdd() {
        this.resetItemsForm()
        //this.itemsForm = Object.assign(this.itemsForm, this.selectTreeNodeData)
        this.dialogItemsFormVisible = true
        this.$nextTick(() => {
          this.$refs['itemsForm'].clearValidate()
        })
      },

      handleUpdateItems(row) {
        this.resetItemsForm()
        this.itemsForm = Object.assign(this.itemsForm, row)
        this.dialogItemsFormVisible = true
        this.$nextTick(() => {
          this.$refs['itemsForm'].clearValidate()
        })
      },

      handleDeleteItems(row) {
        let that = this
        calculateItemDel(row.id)
          .then(response => {
            that.calculateDetailFun(that.chargeId, that.calculateForm.cateId)
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
          })
          .catch(err => {
            console.log(err)
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      },

      //保存计算公式明细
      saveItemFun() {
        let that = this
        this.$refs['itemsForm'].validate(valid => {
          if (valid) {
            that.saveItemsLoading = true
            console.log(this.itemsForm)
            calculateItemSave(this.itemsForm)
              .then(response => {
                that.dialogItemsFormVisible = false
                that.saveItemsLoading = false
                that.calculateDetailFun(that.chargeId, that.calculateForm.cateId)
                this.$notify.success({
                  title: '成功',
                  message: '操作成功'
                })
              })
              .catch(err => {
                that.saveItemsLoading = false
                console.log(err)
                this.$notify.error({
                  title: '失败',
                  message: response.data.errmsg
                })
              })
          }
        })
      }
    }
  }
</script>
